﻿///*
//   @Description:agency员工管理js
//   @Author:wk
//   @Date:2014-08-10 
// */
var employeeIndex = {};


//搜索人员信息后将搜索到的总人数传到主页面显示
employeeIndex.findUsers = function () {
    var totalCount = $("#hiddTotalCount").val();
    $(".totalCount").text(totalCount);
    other.hideLoaderMask();
};


//动态添加部门和角色
employeeIndex.addDepartRole = function () {
    $(".addDepartRole").bind("click", function () {
        //添加的时候隐藏锁定状态
        $(".departAndRolehtml .lockFlag").hide();
        $("#spanTest").find(".departAndRole").append($(".departAndRolehtml").html());
        var i = 0;
        $("#spanTest").find(".departAndRole > div").each(function () {
            i++;
            if (i > 1) {
                var lastDepartName = $(this).find(".addEmployeeDeparthidd").unbind();
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").unbind();

                var lastDepartName = $(this).find(".addEmployeeDeparthidd").attr("id", "txtAddEmployeeDepart" + i);
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").attr("id", "txtAddEmployeeDepartKey" + i);
                //每次添加都会给一个新的ID
                EmployeePrompt.getDepartAndEmployeeByInput(lastDepartName.attr("id"), lastDepartKey.attr("id"), null, null, false, false, 1, null, "");
            }
        });
    })
}
//添加员工相关方法结束 end


//获取选中记录的KeyId
employeeIndex.GetEmployeeKeys = function () {
    var employeeKeyId = "";
    $("#BlackListTab .checkStaff:checked").each(function () {
        employeeKeyId += $(this).val() + ",";
    });
    return employeeKeyId;
}
//按钮状态切换
employeeIndex.ModifyBtnStatus = function (selector, addclass, removeclass) {
    //变化按钮状态
    selector.addClass(addclass);
    selector.removeClass(removeclass);
};

//转移员工使用的方法 start
//转移员工的tab标签切换方法
employeeIndex.transferStaffTab = function () {
    var editTabMenu = $("#spanTransferStaff .tab-nav li");
    var editTabCont = $("#spanTransferStaff .tab-bd .tab-panel");
    editTabMenu.each(function () {
        $(this).click(function () {
            var index = editTabMenu.index(this);
            $(this).addClass("current").siblings().removeClass("current");
            editTabCont.eq(index).css("display", "block").siblings().css("display", "none");
        });
    });
};
employeeIndex.initTransferStaffTab = function (titleID, contentID) {
    var option = {
        titleID: titleID,
        contentID: contentID,
        currentClassName: "current",
        titleFun: employeeIndex.getTitles,
        urlFun: employeeIndex.getTabUrl,
        dataFun: employeeIndex.getData,
        isIframe: true,
        contentFun: null
    };
    tabHelper(option);
}
employeeIndex.getTitles = function () {
    return ["全部房源", "全部客源", "全部钥匙", "全部实勘", "全部签约", "全部转介房", "全部业绩声明"];
}
var userKeyId;
var depatKeyId = "";
employeeIndex.getTabUrl = function (tabname) {
    var urlNum = window.location.href.split('=')[1];
    if (tabname == "全部客源") {
        return "/system/all-inquiry?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部房源") {
        return "/system/all-property?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部钥匙") {
        return "/system/all-key?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部实勘") {
        return "/system/all-real?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部转介房") {
        return "/system/all-propertyMyTurn?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部签约") {
        return "/system/all-onlyTrust?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部业绩声明") {
        return "/system/all-performances?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
};
employeeIndex.getData = function (tabname) {
    return [{ name: "key", value: tabname }];
}

//confirm点击确定执行的回调函数
employeeIndex.UpdateEmployeeStutas = function (employeeKeyId) {
    $('#userStatusModify i').attr('class', 'icon-statusModify');
    $(".statusModify").hide();
    var employeeStutas = $("#inquiryStatusKeyIdAll input[type=radio]:checked").val();
    var reqData = {
        "employeeStutas": employeeStutas,
        "employeeKeyId": employeeKeyId
    };
    $.AjaxAgency("/system/UpdateEmployeeStutas", reqData, function (data) {
        if (data == "OK") {
            $('#btnChangeCustomerStatu').removeAttr('disabled');
            $.OKDialogAgency('<div class="tc">操作成功！</div>', '提示', function () {
                $(".userSubmit").submit();
            });
        }
        else {
            $.OKDialogAgency('<div class="tc">' + data + '</div>');
        }
    });
};


$(function () {

    ////初始化绑定用户的智能提示（用于员工列表页员工搜索框）
    //EmployeePrompt.getEmployeeByInput("txtEmployeeName", "CreateChiefKeyId", false, 'private', null, true);
    //初始化部门绑定的智能提示（用于员工列表页员工搜索框）
    EmployeePrompt.getDepartAndEmployeeByInput("txtDepartmentName", "hidDepartmentId", "txtEmployeeName", "hidUserId", false, 'private', 1, '业务员姓名', '请输入部门名称', true,true);
    //EmployeePrompt.getDepartAndEmployeeByInput('txtDepartmentName', 'txtDepartmentKeyId', 'txtEmployeeName', 'txtTakeSeeUserKeyId', false, 'private', SearchRank, "请输入业务姓名", "请输入部门名称", true, true);

    //添加黑名单相关方法开始 start
    //新增黑名单
    $('#addEmployee').unbind('click');
    $("#addEmployee").bind("click", function () {
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogProprietorEmployee",
            lock: true,
            title: "新增黑名单",
            content: '<div id="spanTest">' + $(".addStaff").html() + '</div>'
        });

        //当失去焦点时做非空验证
        employeeIndex.verify("#spanTest input[isnotnull=1]", "#spanTest select[isnotnull=1]", "#spanTest input[numlength=6]", "#spanTest input[issame=1]");
        //表单验证
        agencyVerify.nonnegativeIntInput("#addPackageCount");
        $.inputStatistics("ReasonTextarea", 500);
        //电话只能输入数字
        agencyVerify.greaterThanEqualZero("#isphonenumber", false);
        
        //点击添加部门的文本框
        employeeIndex.addDepartRole();
        //添加人员数据
        $('.addEmployeeSubmit').unbind('click');
        $(".addEmployeeSubmit").click(function () {

            //提交前先做验证
            if (employeeIndex.clickVerify("#spanTest .addEmployeeDepartKeyhidd", "#spanTest input[isUserNoSame=1]", "#spanTest input[isnotnull=1]", "#spanTest select[isnotnull=1]", "#spanTest input[numlength=6]", "#spanTest input[issame=1]", "#spanTest .checkError")) {
                ////做手机号验证
                var tel = $("#isphonenumber").val(); //获取手机号
                if (tel=="") {
                    return
                }
                
                //处理文本域输入纯空格问题
                    if ($.trim($("textarea").val()) == '') {
                        $.OKDialogAgency("不能全为空格！");
                        return false;
                    }
                //当按钮点击后，按钮变灰别且不可用
                employeeIndex.moreSubmit($("#spanTest .addEmployeeSubmit"), "btn-red", "btn-gray", true);
                //获取多个部门和角色组合的值
                var departKeyId = [], departNames = [], roleKeyId = [];
                $("#spanTest .departAndRole").find(".info-list").each(function () {
                    departKeyId[departKeyId.length] = $(this).find(".addEmployeeDepartKeyhidd").val();
                    departNames[departNames.length] = $(this).find(".addEmployeeDeparthidd").val();
                    roleKeyId[roleKeyId.length] = $(this).find(".EmployeeRole").val()
                });
                //员工编号
                var phone = $("#spanTest").find(".EmployeeNo").val();
                //员工名称
                var reason = $("#spanTest").find(".EmployeeName").val();

                var reqData = {
                    "Phone": phone,
                    "Reason": reason,
                };
                $.AjaxAgency("/customer/add-black-list", reqData, function (data) {
                    if (data == "ok") {
                        $.OKDialogAgency('<div class="tc">添加成功！</div>', '提示', function () {
                            art.dialog.get("dialogProprietorEmployee").close();
                            $("#searchForm").submit();
                        });
                    }
                    else {
                        $.OKDialogAgency('<div class="tc">' + data + '</div>');
                    }
                });
            }
        });
    });

    //根据选择的查询项调用不同的数据接口（条件搜索）
    $(".findType").change(function () {
        //每次选择查询类型先清除文本框的数据
        var findTypeValue = $(".findType").val();
        if (findTypeValue == "Ekey") {
            $(".employee").css("display", "block");
            $(".depart").css("display", "none");

            //调用员工的智能提示的接口
            $("#txtfindDepartName").val("");
            $("#txtfindDepartKey").val("");
        }
        else if (findTypeValue == "Dkey") {
            $(".employee").css("display", "none");
            $(".depart").css("display", "block");

            //调用部门智能提示的接口
            $("#txtfindEmployeeName").val("");
            $("#txtfindEmployeeKey").val("");
        }
    });

});

//处理多次按钮提交的问题
employeeIndex.moreSubmit = function (submitSeletor, removeClass, addClass, disabledValue) {

    //点击完按钮后处理不能点
    submitSeletor.attr("disabled", disabledValue);
    submitSeletor.removeClass(removeClass);
    submitSeletor.addClass(addClass);
};


//点击空白处隐藏
employeeIndex.showAndHide = function (selector, id, func, id2) {
    $(document).unbind("click");
    $(document).bind("click", function (e) {
        var divpanel = $("#" + id);
        var tempoint = divpanel.offset();
        if (e.pageX > (tempoint.left + divpanel.width()) || e.pageX < tempoint.left || e.pageY > (tempoint.top + divpanel.height()) || e.pageY < tempoint.top) {
            if (id2) {
                if (e.target != $(selector)[0] && e.target != $('#' + id2)) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                }
            } else {
                if (e.target != $(selector)[0]) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                }
            }

        }
    });
};

//选择时间控件的默认时间转换
employeeIndex.defaultDate = function (mydate) {

    var getFullYear = mydate.getFullYear();
    var getMonth = (mydate.getMonth() + 1);
    var getDate = mydate.getDate();
    var getHours = mydate.getHours();
    var getMinutes = mydate.getMinutes();

    if (getMonth.toString().length == 1) {
        getMonth = "0" + getMonth;
    }
    if (getDate.toString().length == 1) {
        getDate = "0" + getDate;
    }
    if (getHours.toString().length == 1) {
        getHours = "0" + getHours;
    }
    if (getMinutes.toString().length == 1) {
        getMinutes = "0" + getMinutes;
    }

    return getFullYear + "-" + getMonth + "-" + getDate;
};


//给下拉框动态绑定角色
employeeIndex.getRoles = function (selector, isBind, selectValue) {
    //开始就加载所有的角色信息
    $.AjaxAgency("/System/get-all-role", null, function (data) {
        if (data != null) {
            for (var k = 0; k < data.Result.length; k++) {
                selector.append('<option value="' + data.Result[k].KeyId + '">' + data.Result[k].RoleName + '</option>');
            }
        }
        else {
            $.OKDialogAgency('<div class="tc">' + data + '</div>');
        }
        //编辑时绑定值
        if (isBind) {
            selector.val(selectValue);
        }
    });

};

//Blur事件输入框验证  reserve Property
employeeIndex.verify = function (isnotnullSelector, isselectnotnullSelector, numlengthSelector, issanmeSelect) {

    //不能为空的验证
    agencyVerify.notNullInput(null, isnotnullSelector, true, "blur");
    //验证下拉框不能为空的验证
    agencyVerify.notNullInput(null, isselectnotnullSelector, true, "change");
    //验证输入的部门是否有重复的
    agencyVerify.NoInputSame(".departAndRole", issanmeSelect, "blur", "部门名称不能重复");

    //验证密码只能使6到14位
    agencyVerify.regexCheck(null, numlengthSelector, /^.{6,14}$/, "长度为6到14位", false, "blur");
};
//按钮Click事件验证
employeeIndex.clickVerify = function (ishiddenSelector, isnamesameSelector, isnotnullSelector, isselectnotnullSelector, numlengthSelector, issanmeSelect, ischeckSelector, EmployeeNo) {

    //验证密码位数
    $(isnotnullSelector).blur();
    //验证下拉框不能为空的验证
    $(isselectnotnullSelector).change();
    $(numlengthSelector).blur();
    $(issanmeSelect).blur();
    // $(isnamesameSelector).blur();
    if ($(ischeckSelector).length > 0) {
        return false;
    }
    else {

        //if (!$(isnotnullSelector).val()) {
        //    $.OKDialogAgency('<div class="tc">你确定要添加此黑名单吗？</div>');
        //    return false;
        //} 
        //else {
            return true;
        //}
    }
};

//格式化时间
employeeIndex.formatDate = function (value) {
    var date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
    return employeeIndex.defaultDate(date);
};

//验证重置密码非空和密码与确认密码是否一致
employeeIndex.clickVerifyResetPWD = function (EmployeePWDSelector, confirmEmployeePWDSelector, isnotnullSelector) {
    $(isnotnullSelector).blur();
    confirmEmployeePWDSelector.blur(function () {
        if (confirmEmployeePWDSelector.val() != EmployeePWDSelector.val()) {
            if (confirmEmployeePWDSelector.next().attr("class") != "wrong") {
                confirmEmployeePWDSelector.after(agencyVerify.greatErrorHtml(confirmEmployeePWDSelector, '确认密码与密码不一致!'));
                confirmEmployeePWDSelector.addClass("checkError");
                confirmEmployeePWDSelector.focus();
            }
        }
        else {
            if (confirmEmployeePWDSelector.next().attr("class") == "wrong" && confirmEmployeePWDSelector.next().text() == "确认密码与密码不一致") {
                confirmEmployeePWDSelector.next().remove();
                $(confirmEmployeePWDSelector).removeClass("checkError");
                $(confirmEmployeePWDSelector).change();

            }
        }
    });
    if ($("#spanResetmployeePwd .checkError").length > 0) {
        return false;
    }
    else {
        return true;
    }
};

//拼接checkbox展示该人的多个部门（角色）
employeeIndex.ShowUserDepatRole = function (userDepatRoleCheckSelector, userKeyId) {
    var reqData = {
        "userId": userKeyId
    };
    $.AjaxAgency("/System/get-user-depat-roles", reqData, function (data) {
        if (data.Flag) {
            if (data.Result != null && data.Result.length > 0) {
                $(userDepatRoleCheckSelector).empty();
                for (var i = 0; i < data.Result.length; i++) {
                    if (data.Result[i].DepartmentKeyId != undefined) {
                        if (!data.Result[i].LockUserDepatFlag) {
                            $(userDepatRoleCheckSelector).append("<label><input type=\"checkbox\" value=\"" + data.Result[i].DepartmentKeyId + "\" />[" + data.Result[i].DepartmentName + "]" + "[" + data.Result[i].RoleName + "]</label>");
                        }
                        else {
                            $(userDepatRoleCheckSelector).append("<label style=\"display:none\"><input type=\"checkbox\" value=\"" + data.Result[i].DepartmentKeyId + "\" />[" + data.Result[i].DepartmentName + "]" + "[" + data.Result[i].RoleName + "]</label>");
                        }
                    }
                }
            }
        }
        else {
            $.OKDialogAgency('<div class="tc">' + data + '</div>');
        }

    });
}

//根据部门过滤数据
employeeIndex.GetResourceDataByDepatKey = function () {
    //通过部门过滤资源数据
    $("#spanTransferStaff .userDepatRoleCheck").click(function () {
        var depats = [];
        $(this).find("input[type=checkbox]:checked").each(function () {
            depats[depats.length] = $(this).val();
        });
        depatKeyId = depats.join(",");
        $("#spanTransferStaff .transferDepatKeyIds").val(depatKeyId);
        //动态绑定Tab页切换
        var frameUrl = parent.$("#contentdiv #tabmenuiframe").attr("src");
        parent.$("#contentdiv #tabmenuiframe").attr("src", frameUrl.toString().split("?")[0] + "?userId=" + userKeyId + "&depatId=" + depatKeyId);
    });

};

//编辑员工相关方法开始 start
employeeIndex.init = function () {

    //翻页初始化验证按钮的状态
    if ($("#BlackListTab .checkStaff:checked").length == 0) {
        employeeIndex.ModifyBtnStatus($('#userStatusModify i'), "icon-statusModify", "icon-statusModify-on");
        employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
    }

    //员工全选/取消全选
    $("#BlackListTab .checkAll").click(function () {
        if ($("#BlackListTab .checkAll").attr("checked") == "checked") {
            $("#BlackListTab .checkStaff").each(function () {
                $(this).attr("checked", "true");
            });
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "btn-blue", "edit-btn-gray");
            // employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "btn-blue", "edit-btn-gray");
        }
        else {
            $("#BlackListTab .checkStaff").each(function () {
                $(this).removeAttr("checked");
            });
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
            // employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
        }
    });

    //选择后按钮状态变化
    $("#BlackListTab .checkStaff").click(function () {
        if ($("#BlackListTab .checkStaff:checked").length > 0) {
            //变化按钮状态
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "btn-blue", "edit-btn-gray");
            if ($("#BlackListTab .checkStaff:checked").length == 1) {
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "btn-blue", "edit-btn-gray");
            }
            else {
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
            }
        }
        else {
            if ($("#BlackListTab .checkStaff:checked").length == 0) {
                employeeIndex.ModifyBtnStatus($('#userStatusModify i'), "icon-statusModify", "icon-statusModify-on");
                $(".statusModify").hide();
                employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
            }
        }
    });

    //删除黑名单
    $("#BlackListTab #DeleteBlacklist").bind("click", function () {
        //获取删除的黑名单ID
        var userKeyId = $(this).attr("data-keyid");
        $.OKCancelDialogAgency('<div class="tc">确认删除该黑名单吗？</div>', "删除", true, function () {
            var url = "/Customer/remove-black-list";
            var reqData = {
                "keyIds": userKeyId
            };
            $.AjaxAgency(url, reqData, function (data) {
                if (data == "ok") {
                    $.OKDialogAgency('<div class="tc">删除成功！</div>', '提示', function () {
                        window.location.reload();
                        //window.location = "/customer/black-list";
                    });                    
                }                
                else {
                    $.OKDialogAgency('<div class="tc">' + data + '</div>');
                }
            });
        }, null);
    });

    //转移员工 end
    //动态添加部门和角色
    employeeIndex.editDepartRole = function () {
        $("#spanEditemployee").find(".editDepartRole").bind("click", function () {

            //编辑员工的部门时将锁定的下拉框显示出来
            $(".departAndRolehtml .lockFlag").show();
            $("#spanEditemployee").find(".departAndRole").append($(".departAndRolehtml").html());
            var i = 0;
            $("#spanEditemployee").find(".departAndRole > div").each(function () {
                i++;
                var lastDepartName = $(this).find(".addEmployeeDeparthidd").unbind();
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").unbind();

                var lastDepartName = $(this).find(".addEmployeeDeparthidd").attr("id", "txtEditEmployeeDepart" + i);
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").attr("id", "txtEditEmployeeDepartKey" + i);
                //每次添加都会给一个新的ID
                EmployeePrompt.getDepartAndEmployeeByInput(lastDepartName.attr("id"), lastDepartKey.attr("id"), null, null, false, false, 1, null, "");
            })
        });
    }
    //编辑员工相关方法结束 end
};
